﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace MyVBAScript
{
    public partial class frmMain : Form
    {
        /// <summary>
        /// 脚本中使用的文档对象类型,本对象是对 frmMain 的一个封装
        /// </summary>
        public class DocumentClass
        {
            /// <summary>
            /// 初始化对象
            /// </summary>
            /// <param name="frm"></param>
            internal DocumentClass(frmMain frm)
            {
                myForm = frm;
            }

            internal frmMain myForm = null;
            /// <summary>
            /// 设置或返回文档文本内容
            /// </summary>
            public string Text
            {
                get
                {
                    return myForm.txtEditor.Text;
                }
                set
                {
                    myForm.txtEditor.Text = value;
                }
            }
            /// <summary>
            /// 向文档添加文本内容
            /// </summary>
            /// <param name="text">要添加的文本内容</param>
            public void AppendText(string text)
            {
                myForm.txtEditor.AppendText(text);
            }
            /// <summary>
            /// 设置获得文档中选择的部分
            /// </summary>
            public string Selection
            {
                get { return myForm.txtEditor.SelectedText; }
                set { myForm.txtEditor.SelectedText = value; }
            }
            /// <summary>
            /// 文档文件名
            /// </summary>
            public string FileName
            {
                get { return myForm.FileName; }
            }
            /// <summary>
            /// 新建文档
            /// </summary>
            /// <returns>操作是否成功</returns>
            public bool New()
            {
                return myForm.Function_New();
            }
            /// <summary>
            /// 保存文档
            /// </summary>
            /// <returns>操作是否成功</returns>
            public bool Save()
            {
                return myForm.Function_Save();
            }
            /// <summary>
            /// 文档另存为
            /// </summary>
            /// <returns>操作是否成功</returns>
            public bool SaveAs()
            {
                return myForm.Function_SaveAs();
            }
            /// <summary>
            /// 打开文件
            /// </summary>
            /// <returns>操作是否成功</returns>
            public bool Open()
            {
                return myForm.Function_Open();
            }
            /// <summary>
            /// 剪切
            /// </summary>
            public void Cut()
            {
                myForm.Function_Cut();
            }
            /// <summary>
            /// 复制
            /// </summary>
            public void Copy()
            {
                myForm.Function_Copy();
            }
            /// <summary>
            /// 粘帖
            /// </summary>
            public void Paste()
            {
                myForm.Function_Paste();
            }
            /// <summary>
            /// 删除
            /// </summary>
            public void Delete()
            {
                myForm.Function_Delete();
            }
            /// <summary>
            /// 全选
            /// </summary>
            public void SelectAll()
            {
                myForm.Function_SelectAll();
            }

        }//public class DocumentClass

        public frmMain()
        {
            InitializeComponent();

            // 初始化脚本引擎
        }


        private void frmMain_Load(object sender, EventArgs e)
        {
            //初始化窗体

            // 创建脚本引擎
            myVBAEngine = new XVBAEngine();
            myVBAEngine.AddReferenceAssemblyByType(this.GetType());
            myVBAEngine.VBCompilerImports.Add("MyVBAScript.Global");
            // 设置脚本引擎全局对象
            MyVBAScript.Global.GlobalObject.myWindow = new XVBAWindowObject(this, myVBAEngine, this.Text);
            MyVBAScript.Global.GlobalObject.myDocument = new DocumentClass(this);
            // 加载演示脚本文本
            string strDemoVBS = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "demo.vbs");
            if (System.IO.File.Exists(strDemoVBS))
            {
                System.IO.StreamReader reader = new System.IO.StreamReader(strDemoVBS, System.Text.Encoding.GetEncoding("gb2312"));
                string script = reader.ReadToEnd();
                reader.Close();
                myVBAEngine.ScriptText = script;
                if (myVBAEngine.Compile() == false)
                {
                    this.txtEditor.Text = "编译默认脚本错误:\r\n" + myVBAEngine.CompilerOutput;
                }
                // 刷新脚本方法列表
                this.RefreshScriptMethodList();
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (QuerySave() == false)
            {
                e.Cancel = true;
                return;
            }
            base.OnClosing(e);
            myVBAEngine.Close();
        }

        private XVBAEngine myVBAEngine = null;

        #region 工具条按钮事件处理

        private void btnNew_Click(object sender, EventArgs e)
        {
            Function_New();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            Function_Open();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Function_Save();
        }

        private void btnSaveAs_Click(object sender, EventArgs e)
        {
            Function_SaveAs();
        }

        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            Function_SelectAll();
        }

        private void btnCut_Click(object sender, EventArgs e)
        {
            Function_Cut();
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            Function_Copy();
        }

        private void btnPaste_Click(object sender, EventArgs e)
        {
            Function_Paste();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            Function_Delete();
        }
        /// <summary>
        /// 编辑脚本按钮事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLoadScript_Click(object sender, EventArgs e)
        {
            //显示脚本文本编辑对话框
            using (dlgEditScript dlg = new dlgEditScript())
            {
                int VersionBack = myVBAEngine.ScriptVersion;
                dlg.VBAEngine = this.myVBAEngine;
                dlg.ShowDialog(this);
                if (VersionBack != myVBAEngine.ScriptVersion)
                {
                    // 若脚本引擎内容发生改变则刷新脚本方法下拉菜单项目
                    RefreshScriptMethodList();
                }
            }
        }
        /// <summary>
        /// 刷新“运行脚本”按钮的下拉菜单项目，显示所有可以执行的脚本方法名称
        /// </summary>
        private void RefreshScriptMethodList()
        {
            // 情况脚本方法名称列表
            this.btnRunScript.DropDownItems.Clear();
            // 获得脚本引擎中所有的脚本方法名称
            string[] names = myVBAEngine.ScriptMethodNames;
            if (names != null && names.Length > 0)
            {
                // 将脚本方法名称添加到“运行脚本”的下拉菜单项目中
                foreach (string name in names)
                {
                    ToolStripMenuItem item = new ToolStripMenuItem();
                    item.Text = name;
                    item.Click += new EventHandler(ScriptItem_Click);
                    btnRunScript.DropDownItems.Add(item);
                }
                myStatusLabel.Text = "共加载 " + names.Length + " 个脚本方法";
            }
            else
            {
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.Enabled = false;
                item.Text = "没有加载任何脚本方法";
                btnRunScript.DropDownItems.Add(item);
                myStatusLabel.Text = "没有加载任何脚本方法";
            }
        }
        /// <summary>
        /// 运行脚本的下拉菜单项目点击事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void ScriptItem_Click(object sender, System.EventArgs args)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            try
            {
                // 调用脚本执行指定名称的脚本方法
                myVBAEngine.Execute(item.Text, null, true);
            }
            catch (Exception ext)
            {
                System.Console.WriteLine("执行脚本 " + item.Text + " 错误:" + ext.ToString());
                MessageBox.Show(this, "执行脚本 " + item.Text + " 错误:" + ext.Message);
            }
        }

        #endregion

        private string strFileName = null;
        /// <summary>
        /// 当前操作的文件名
        /// </summary>
        public string FileName
        {
            get { return strFileName; }
            set { strFileName = value; }
        }

        private bool QuerySave()
        {
            if (this.txtEditor.Modified)
            {
                switch (MessageBox.Show(this, "文档已修改，是否保持?", "系统提示", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
                {
                    case DialogResult.Yes:
                        if (Function_Save() == false)
                        {
                            return false;
                        }
                        return true;
                    case DialogResult.No:
                        return true;
                    case DialogResult.Cancel:
                        return false;
                }
            }
            return true;
        }

        #region 操作文档的功能函数

        /// <summary>
        /// 执行新建文档
        /// </summary>
        public bool Function_New()
        {
            if (QuerySave())
            {
                txtEditor.Text = "";
                txtEditor.Modified = false;
                strFileName = null;
                return true;
            }
            return false;
        }

        /// <summary>
        /// 执行打开文件操作
        /// </summary>
        public bool Function_Open()
        {
            if (QuerySave() == false)
            {
                return false;
            }
            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.Filter = "文本文件(*.txt)|*.txt|所有文件|*.*";
                dlg.CheckPathExists = true;
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    System.IO.StreamReader reader = new System.IO.StreamReader(
                        dlg.FileName, System.Text.Encoding.GetEncoding("gb2312"));
                    txtEditor.Text = reader.ReadToEnd();
                    reader.Close();
                    strFileName = dlg.FileName;
                    txtEditor.Modified = false;
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 执行保存文档操作
        /// </summary>
        /// <returns>操作是否成功</returns>
        public bool Function_Save()
        {
            if (strFileName == null)
            {
                using (SaveFileDialog dlg = new SaveFileDialog())
                {
                    dlg.Filter = "文本文件(*.txt)|*.txt|所有文件|*.*";
                    dlg.CheckPathExists = true;
                    dlg.OverwritePrompt = true;
                    if (dlg.ShowDialog(this) == DialogResult.OK)
                    {
                        strFileName = dlg.FileName;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            System.IO.StreamWriter writer = new System.IO.StreamWriter(
                strFileName, false, System.Text.Encoding.GetEncoding("gb2312"));
            writer.Write(this.txtEditor.Text);
            writer.Close();
            this.txtEditor.Modified = false;
            return true;
        }

        /// <summary>
        /// 执行另存为操作
        /// </summary>
        public bool Function_SaveAs()
        {
            using (SaveFileDialog dlg = new SaveFileDialog())
            {
                dlg.Filter = "文本文件(*.txt)|*.txt|所有文件|*.*";
                dlg.CheckPathExists = true;
                dlg.OverwritePrompt = true;
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    strFileName = dlg.FileName;
                    System.IO.StreamWriter writer = new System.IO.StreamWriter(
                        strFileName, false, System.Text.Encoding.GetEncoding("gb2312"));
                    writer.Write(this.txtEditor.Text);
                    writer.Close();
                    this.txtEditor.Modified = false;
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 执行全选操作
        /// </summary>
        public void Function_SelectAll()
        {
            txtEditor.SelectAll();
        }

        /// <summary>
        /// 执行剪切操作
        /// </summary>
        public void Function_Cut()
        {
            txtEditor.Cut();
        }

        /// <summary>
        /// 执行复制操作
        /// </summary>
        public void Function_Copy()
        {
            txtEditor.Copy();
        }

        /// <summary>
        /// 执行粘帖操作
        /// </summary>
        public void Function_Paste()
        {
            txtEditor.Paste();
        }
        /// <summary>
        /// 执行删除操作
        /// </summary>
        public void Function_Delete()
        {
            txtEditor.SelectedText = "";
        }

        #endregion

        private void myLinkLabel_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.xdesigner.cn");
        }


    }
}